<?php
namespace app\common\model;
use think\Model;
use app\common\model\Game;

class Attention extends Model
{
	// 表名
    protected $name = 'attention';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    // 追加属性
    protected $append = [];

    /**
     * 获取用户关注
     */
    public function getAttention($userId)
    {
    	if (!$userId) {
    		return false;
    	}

    	$data = self::where('user_id', (int)$userId)->field('game_id')->select();
    	$result = [];
    	if ($data) {
    		$gameIds = [];
    		foreach ($data as $value) {
    			$gameIds[] = $value->game_id;
    		}

            $field = 'game_id,already_amount,total_amount,cost_time,total_time,status,create_time';
    		$gameList = Game::where('game_id', 'in', $gameIds)->field($field)->select();
    		foreach ($gameList as $info) {
                if (empty($info->cost_time)) {
                    $costTime = time() - $info->create_time;
                } else {
                    $costTime = $info->cost_time;
                }

    			$result[] = [
                    'game_id'        => $info->game_id,
    				'already_amount' => $info->already_amount,
    				'total_amount'   => $info->total_amount,
    				'cost_time'      => round($costTime/3600, 1) . 'h',
    				'total_time'     => round($info->total_time/3600, 1) . 'h',
                    'status'         => $info->status,
    			];
    		}

    		unset($gameList);
    	}

    	return $result;
    }

    /**
     * 添加关注
     */
    public function addAttention($userId, $gameId)
    {
        if (!$userId || !$gameId) {
            return false;
        }

        $this->user_id = (int)$userId;
        $this->game_id = (int)$gameId;
        $this->save();
        // 获取自增ID
        return $this->id ? $this->id : false;
    }

    /**
     * 获取单个关注
     */
    public function getInfo($where)
    {
        if (!$where) {
            return false;
        }

        return $this->where($where)->find();
    }
}